<script lang="ts" setup>
import type {
  OnActionClickParams,
  VxeTableGridOptions,
} from '#/adapter/vxe-table';
import type { AutoInspectionItemModel } from '#/api/equipment/models';

import { reactive } from 'vue';

import { useVbenDrawer, useVbenModal } from '@vben/common-ui';

import { Button, message } from 'ant-design-vue';

import { useVbenVxeGrid } from '#/adapter/vxe-table';
import {
  deleteAutoInspectionItemApi,
  getAutoInspectionItemListApi,
} from '#/api/equipment/autoInspectionItem';
import { $t } from '#/locales';

import { useColumns } from './data';
import Form from './modules/form.vue';

const state = reactive({
  planId: 0,
  dataList: [] as AutoInspectionItemModel[],
});

const [FormModal, formModalApi] = useVbenModal({
  connectedComponent: Form,
  destroyOnClose: true,
});

/**
 * 创建自动点检项
 */
function onCreate() {
  formModalApi.setData({ planId: state.planId }).open();
}

/**
 * 编辑自动点检项
 */
function onEdit(row: AutoInspectionItemModel) {
  formModalApi.setData({ values: row, planId: state.planId }).open();
}

/**
 * 删除自动点检项
 */
function onDelete(row: AutoInspectionItemModel) {
  const hideLoading = message.loading({
    content: $t('ui.actionMessage.deleting', [row.subjectName]),
    duration: 0,
    key: 'action_process_msg',
  });
  deleteAutoInspectionItemApi(row.id)
    .then(() => {
      message.success({
        content: $t('ui.actionMessage.deleteSuccess', [row.subjectName]),
        key: 'action_process_msg',
      });
      refreshGrid();
    })
    .catch(() => {
      hideLoading();
    });
}

/**
 * 表格操作按钮的回调函数
 */
function onActionClick({
  code,
  row,
}: OnActionClickParams<AutoInspectionItemModel>) {
  switch (code) {
    case 'delete': {
      onDelete(row);
      break;
    }
    case 'edit': {
      onEdit(row);
      break;
    }
  }
}

const [Grid] = useVbenVxeGrid({
  gridOptions: {
    columns: useColumns(onActionClick),
    data: state.dataList,
    border: true,
    stripe: true,
    pagerConfig: {
      enabled: false,
    },
  } as VxeTableGridOptions,
});

const [Drawer, drawerApi] = useVbenDrawer({
  onConfirm() {
    drawerApi.close();
  },
  async onOpenChange(isOpen: boolean) {
    if (isOpen) {
      const { id } = drawerApi.getData<Record<string, any>>();
      state.planId = id;
      await refreshGrid();
    }
  },
  title: '自动点检项目设置',
  showCancelButton: false,
  showConfirmButton: false,
});

/** 加载数据 */
async function refreshGrid() {
  state.dataList.length = 0; // 清空数组
  const data = await getAutoInspectionItemListApi(state.planId);
  state.dataList.push(...data);
}
</script>

<template>
  <Drawer>
    <div class="h-full">
      <FormModal @success="refreshGrid()" />
      <Grid>
        <template #toolbar-tools>
          <Button type="primary" @click="onCreate"> 新增点检项 </Button>
        </template>
      </Grid>
    </div>
  </Drawer>
</template>
